package com.lk;

import jdk.nashorn.internal.runtime.FindProperty;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写、写写是互斥的
 * 读读不互斥
 */
public class TestReadWriterLock {
    public static void main(String[] args) {
        ReadWriterDemo readWriterDemo = new ReadWriterDemo();

        new Thread(()->{
            readWriterDemo.writer(100);
        },"writer").start();

        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                readWriterDemo.get();
            }).start();
        }
    }
}

class ReadWriterDemo{

    private int num=0;

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void get(){
        System.out.println(1111);
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+" : "+num);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }

    public void writer(int num){
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName());
            this.num = num;
        }finally {
            lock.writeLock().unlock();
        }
    }

}